<template>
  <!-- 负责检验 -->
  <div class="my-form-item">
    <div class="form-item-main">
      <label v-if="label" :class="[
          'form-item-label',
          { 'after-star': afterStar },
          { 'before-star': beforeStar },
          { 'required-label': isRquiredLabel },
        ]">{{ label }}</label>
      <slot></slot>
    </div>
    <p v-if="errorMessage" class="error-message">
      <i class="iconfont iconcard-btn-tanhao"></i>
      {{ errorMessage }}
    </p>
  </div>
</template>

<script>
import Validator from 'async-validator'
export default {
  inject: ['form'],
  props: {
    label: {
      type: String,
      default: '',
    },
    prop: {
      type: String,
      default: '',
    },
    useInput: {
      type: Boolean,
      default: false,
    },
    beforeStar: {
      type: Boolean,
      default: false,
    },
    afterStar: {
      type: Boolean,
      default: false,
    },
    isRquiredLabel: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      errorMessage: '',
    }
  },
  created() {
    this.$on('validate', this.validate)
  },
  methods: {
    validate() {
      return new Promise((resolve) => {
        // 校验规则制定
        const descriptor = { [this.prop]: this.form.rules[this.prop] }
        if (!descriptor[this.prop]) return
        // 创建校验器
        const validator = new Validator(descriptor)
        // 执行校验
        validator.validate(
          // 校验的属性
          { [this.prop]: this.form.model[this.prop] },
          (errors) => {
            if (errors) {
              this.errorMessage = errors[0].message
              resolve(false)
            } else {
              this.errorMessage = ''
              resolve(true)
            }
          }
        )
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.my-form-item {
  .form-item-main {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #d0d0d0;
    padding: 0 0.2rem 0 0;
    .form-item-label {
      width: 1.8rem;
      font-size: 0.28rem;
      line-height: 1.05rem;
      text-align: left;
      color: rgba(26, 27, 33, 1);
      &.after-star {
        &::after {
          content: '*';
          color: #e51900;
        }
      }
      &.before-star {
        &::before {
          content: '*';
          color: #e51900;
        }
      }
    }
  }
}
.error-message {
  padding: 0 0.2rem;
  font-size: 0.28rem;
  line-height: 0.6rem;
  color: #e51900;
  text-align: right;
}
</style>
